--[[
    @Author       : GGELUA
    @Date         : 2020-01-08 21:52:58
    @LastEditTime : 2021-05-08 02:20:23
--]]
local _ENV = require("SDL")
IMG_Init()

local SDL纹理 = class"SDL纹理"

local function _载入纹理(rd,a,b,c,d,e)
    if not rd then return end
    local tp = ggetype(a)

    if tp=='number' and type(b)=='number' then--默认渲染区模式,ARGB8888
        return  rd:CreateTexture(a,b,c,d) or error(GetError(),4)--宽度,高度,模式,像素格式
    elseif tp=='string' then--默认可锁定
        if type(b)=='number' and #a==b then--lstring
            local rw = RWFromStr(a)
            return  rw and rd:LoadTexture_RW(rw,c) or error(GetError(),4)
        end
        return rd:LoadTexture(a,b) or error(GetError(),4)--文件,模式
    elseif tp == 'SDL_Texture' then
        return a
    elseif tp == 'SDL_Surface' then
        return rd:CreateTextureFromSurface(a,b) or error(GetError(),4)
    elseif tp == 'SDL图像' and a:取对象() then
        return rd:CreateTextureFromSurface(a:取对象(),b) or error(GetError(),4)
    elseif tp == 'SDL读写' and a:取对象()  then
        return rd:LoadTexture_RW(a:取对象(), b) or error(GetError(),4)
    elseif tp == 'SDL_RWops' then
        return rd:LoadTexture_RW(a, b) or error(GetError(),4)
    elseif a~= nil then
        error('未知模式',4)
    end
end

function SDL纹理:SDL纹理(...)
    ggeassert(SDL._mth == SDL.ThreadID(),"无法在线程中调用",3)
    self._win = SDL._win --默认窗口
    self._tex = _载入纹理(self._win:取渲染器(),...)

    if ggetype(self._tex)=='SDL_Texture' then
        self._win._texs[self] = self._tex
        self._format,self._access,self.宽度,self.高度 = self._tex:QueryTexture()
        if self._access==TEXTUREACCESS_TARGET then
            self._tex:SetTextureBlendMode(BLENDMODE_BLEND)
        end
    end
end

-- function SDL纹理:更新(pixels,pitch)
--     self._tex:UpdateTexture(nil,pixels,pitch)
--     --self._tex:UpdateYUVTexture()
-- end

function SDL纹理:取对象()
    return self._tex
end

function SDL纹理:取模式()
    return self._access
end

function SDL纹理:锁定(x,y,w,h)
    if self._tex then
        if self._access ~= TEXTUREACCESS_STREAMING then
            error('"无法锁定"',2)
        end
        local rect
        if x and y and w and h then
            rect = CreateRect(x,y,w,h)
        end
        return self._tex:LockTexture(rect)
    end
end

function SDL纹理:解锁()
    if self._tex then
        self._tex:UnlockTexture()
    end
    return self
end

function SDL纹理:置过滤(v)
    if self._tex then
        self._tex:SetTextureScaleMode(v)
    end
    return self
end

function SDL纹理:到精灵()
    return require("SDL.精灵")(self)
end

function SDL纹理:渲染清除(r,g,b,a)
    if self._access==TEXTUREACCESS_TARGET then
        self._win:置渲染区(self._tex)
        return self._win:渲染清除(r,g,b,a)
    end
end

function SDL纹理:渲染结束()
    self._win:置渲染区()
end
return SDL纹理